package com.um.springboot.starter.configuration;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringBootVersion;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import java.lang.reflect.Method;

/**
 * @author 邓南辉
 * @date 2019/12/19
 * @copyright 广州优匠科技有限公司
 */
@Slf4j
@Configuration
public class CorsFilterConfiguration {

    @Bean
    @ConditionalOnMissingBean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig());
        return new CorsFilter(source);
    }

    protected CorsConfiguration buildConfig() {
        CorsConfiguration config = new CorsConfiguration();

        config.setAllowCredentials(true);
        // 1、允许任何域名使用
        if (SpringBootVersion.getVersion().endsWith(".RELEASE")) {
            config.addAllowedOrigin("*"); // 2.4以下版本
        } else {
            // 2.4及以上版本反射调用corsConfiguration.addAllowedOriginPattern("*")
            try {
                Class<? extends CorsConfiguration> clazz = config.getClass();
                Method method = clazz.getDeclaredMethod("addAllowedOriginPattern", String.class);
                method.invoke(config, "*");
            } catch (Exception e) {
                log.error("", e);
            }
        }
        // 2、允许任何头
        config.addAllowedHeader("*");
        // 3、允许任何方法（post、get等）
        config.addAllowedMethod("*");
        // 4、一个小时内相同域名跨域请求不再预检
        config.setMaxAge(3600L);

        return config;
    }
}
